package com.tdkj.service.shop.impl;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;

import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Component;

import com.tdkj.dao.shop.IBeanGoodDao;
import com.tdkj.model.base.BaseEntity;
import com.tdkj.model.common.BeanType;
import com.tdkj.model.shop.BeanEvaluate;
import com.tdkj.model.shop.BeanEvaluateType;
import com.tdkj.model.shop.BeanGood;
import com.tdkj.model.shop.BeanGoodAuction;
import com.tdkj.model.shop.BeanGoodShowcase;
import com.tdkj.model.shop.BeanOrderItem;
import com.tdkj.model.shop.BeanShelf;
import com.tdkj.model.user.BeanUser;
import com.tdkj.service.BaseService;
import com.tdkj.service.ServiceException;
import com.tdkj.service.shop.IBeanGoodService;

@Component
public class BeanGoodServiceImpl extends BaseService implements
		IBeanGoodService {
	
	private  IBeanGoodDao beanGoodDao;
    
	@Resource
	public void setBeanGoodDao(IBeanGoodDao beanGoodDao) {
		this.beanGoodDao = beanGoodDao;
	}

	public IBeanGoodDao getBeanGoodDao() {
		return beanGoodDao;
	}

	@Override
	public BeanGood save(BeanGood good) {
		good.setAuditState("未审核");
		good.setShop(good.getUser().getShop());
		if(good.getCustom().getId() == null){
			good.setCustom(null);
		}
		beanGoodDao.save(good);
		if(good.getSellType() == 1){
			BeanGoodAuction auction = new BeanGoodAuction();
			auction.setGood(good);
			auction.setState("-1");
			auction.setQuantity(1);
			
			beanGoodDao.save(auction);
			
			good.setCurrentAuction(auction);
		}
		
		return good;
	}

	@Override
	public void update(BeanGood good) {
		BeanGood pgood = beanGoodDao.findById(good.getId(), BeanGood.class);
		
		pgood.setType(good.getType());
		pgood.setCode(good.getCode());
		pgood.setDetailDescription(good.getDetailDescription());
		pgood.setImgurl(good.getImgurl());
		pgood.setKeywords(good.getKeywords());
		pgood.setName(good.getName());
		pgood.setPrice(good.getPrice());
		pgood.setQuantity(good.getQuantity());
		pgood.setRateOfIncrease(good.getRateOfIncrease());
		pgood.setSellType(good.getSellType());
		pgood.setUseType(good.getUseType());
		pgood.setColor(good.getColor());
		pgood.setInventory(good.getInventory());
		
		pgood.setEffective(good.getEffective());
		pgood.setInvoice(good.getInvoice());
		pgood.setWarranty(good.getWarranty());
		pgood.setAutomaticRepeat(good.getAutomaticRepeat());
		pgood.setAuditState("0");
		pgood.setSubmitTime(new Timestamp(System.currentTimeMillis()));
		if(pgood.getSellType() == 1 && pgood.getCurrentAuction()==null){
			BeanGoodAuction auction = new BeanGoodAuction();
			auction.setGood(pgood);
			auction.setQuantity(1);
			beanGoodDao.save(auction);
			
			pgood.setCurrentAuction(auction);
		}
	}

	@Override
	public void publish(Long id, Long shelfId) throws ServiceException {
		BeanShelf shelf = beanGoodDao.findById(shelfId, BeanShelf.class);
		
		if(shelf.getQuantity() <= shelf.getGoods().size()){
			throw new ServiceException("货架已满，请购买！");
		}
		
		BeanGood good = beanGoodDao.findById(id, BeanGood.class);
		good.setPublishTime(new Timestamp(System.currentTimeMillis()));
		good.setShelf(shelf);
		good.setShop(shelf.getShop());
		
		if(good.getSellType() == 1  && good.getCurrentAuction()==null){
			
			BeanGoodAuction auction = new BeanGoodAuction();
			auction.setStartTime(new Date(System.currentTimeMillis()));
			auction.setEndTime(new Date(System.currentTimeMillis() + 1000L*24*60*60*good.getEffective()));
			auction.setGood(good);
			auction.setState("0");
			beanGoodDao.save(auction);
			
			good.setCurrentAuction(auction);
			
		}
		if(good.getSellType() == 1){
			good.getCurrentAuction().setState("0");
			good.getCurrentAuction().setStartTime(new Date(System.currentTimeMillis()));
			good.getCurrentAuction().setEndTime(new Date(System.currentTimeMillis() + 1000L*24*60*60*good.getEffective()));
		}
		
	}
	
	@Override
	public void unpublish(Long id) {
		BeanGood good = beanGoodDao.findById(id, BeanGood.class);
		good.setShelf(null);
		good.setShowcase(null);
		
	}

	@Override
	public void createRecommend(Long goodId) throws ServiceException {
		BeanGood good = beanGoodDao.findById(goodId, BeanGood.class);
		BeanGoodShowcase showcase = good.getUser().getShop().getShowcase();
		if(showcase.getQuantity() <= showcase.getGoods().size()){
			throw new ServiceException("推荐已满，请购买！");
		}
		
		good.setShowcase(showcase);
	}

	
	@Override
	public BeanGood getGoodById(Long goodId) {
		beanGoodDao.getSession().clear();
		BeanGood good = beanGoodDao.findById(goodId, BeanGood.class);
		int visitCount = (good.getVisitCount()==null?0:good.getVisitCount()) + 1;
		good.setVisitCount(visitCount);
		return good;
	}
	
	@Override
	public BeanShelf getDefaultShelfByUserId(Long userId){
		BeanShelf shelf = null;
		BeanUser user = beanGoodDao.findById(userId, BeanUser.class);
		List<BeanShelf> shelfs = user.getShop().getShelfs();
		if(shelfs == null){
			shelfs = new ArrayList<BeanShelf>();
			user.getShop().setShelfs(shelfs);
		}
		if(shelfs.size() == 0){
			shelf = new BeanShelf();
			shelf.setShop(user.getShop());
			beanGoodDao.save(shelf);
		}else{
			shelf = shelfs.get(0);
		}
		return shelf;
	}

	@Override
	public void changeAudit(Long id, String auditState) {
		BeanGood good = beanGoodDao.findById(id, BeanGood.class);
		good.setAuditState(auditState);
	}

	@Override
	public void changeAudit(Long[] ids, String auditState) {
		for(Long id : ids){
			BeanGood good = beanGoodDao.findById(id, BeanGood.class);
			good.setAuditState(auditState);
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public void updateInnerTypeSelected(Long innerTypeId, Long userId,
			Long[] selectedIds) {
		BeanType innerType = beanGoodDao.findById(innerTypeId, BeanType.class);
		BeanUser user = beanGoodDao.findById(userId, BeanUser.class);
		
		
		List<BeanGood> selectedGoods = beanGoodDao.getSession().createCriteria(BeanGood.class)
		.add(Restrictions.eq("innerType", innerType))
		.add(Restrictions.isNotNull("shelf"))
		.add(Restrictions.eq("user", user))
		.list();
		Set<Long> oldSelectedGoodIds = new HashSet<Long>();
		Set<Long> newSelectedGoodIds = new HashSet<Long>();
		
		for(BeanGood good : selectedGoods){
			oldSelectedGoodIds.add(good.getId());
		}
		if(selectedIds != null){
			for(Long id : selectedIds){
				newSelectedGoodIds.add(id);
				if(oldSelectedGoodIds.contains(id)){
					continue;
				}
				BeanGood good = beanGoodDao.findById(id, BeanGood.class);
				good.setInnerType(innerType);
			}
		}
		
		for(Long id : oldSelectedGoodIds){
			if(newSelectedGoodIds.contains(id)){
				continue;
			}
			BeanGood good = beanGoodDao.findById(id, BeanGood.class);
			good.setInnerType(null);
		}
	}
	
	
	
	@Override
	public void addEvaluateOfBuyer(Long orderItemId, Long buyerId, Long typeId,
			String content) {
		BeanOrderItem orderItem = beanGoodDao.findById(orderItemId, BeanOrderItem.class);
		if(orderItem.getOrder().getBuyer().getId() == buyerId){
			BeanEvaluateType type = beanGoodDao.findById(typeId, BeanEvaluateType.class);
			
			BeanEvaluate bean = new BeanEvaluate();
			bean.setType(type);
			bean.setContent(content);
			bean.setDateTime(new Timestamp(System.currentTimeMillis()));
			bean.setFlag(0);
			bean.setUser(orderItem.getOrder().getBuyer());
			bean.setToUser(orderItem.getOrder().getSeller());
			beanGoodDao.save(bean);
			
			orderItem.getOrder().getSeller().getShop().setCreditScore(orderItem.getOrder().getSeller().getShop().getCreditScore() + type.getScore());
			orderItem.setIsBuyerEvaluated(true);
			orderItem.setBuyerEvaluate(bean);
		}
	}

	@Override
	public void addEvaluateOfSeller(Long orderItemId, Long sellerId, Long typeId,
			String content) {
		BeanOrderItem orderItem = beanGoodDao.findById(orderItemId, BeanOrderItem.class);
		if(orderItem.getOrder().getSeller().getId() == sellerId){
			BeanEvaluateType type = beanGoodDao.findById(typeId, BeanEvaluateType.class);

			BeanEvaluate bean = new BeanEvaluate();
			bean.setType(type);
			bean.setContent(content);
			bean.setDateTime(new Timestamp(System.currentTimeMillis()));
			bean.setFlag(1);
			bean.setUser(orderItem.getOrder().getSeller());
			bean.setToUser(orderItem.getOrder().getBuyer());
			beanGoodDao.save(bean);
			
			orderItem.getOrder().getBuyer().setCreditScore(orderItem.getOrder().getBuyer().getCreditScore() + type.getScore());
			orderItem.setIsSellerEvaluated(true);
			orderItem.setSellerEvaluate(bean);
		}
	}

	@Override
	public boolean isBuyerEvaluated(Long orderItemId) {
		BeanOrderItem orderItem = beanGoodDao.findById(orderItemId, BeanOrderItem.class);
		return orderItem.getIsBuyerEvaluated()!=null?orderItem.getIsBuyerEvaluated():false;
	}

	@Override
	public boolean isSellerEvaluated(Long orderItemId) {
		BeanOrderItem orderItem = beanGoodDao.findById(orderItemId, BeanOrderItem.class);
		return orderItem.getIsSellerEvaluated()!=null?orderItem.getIsSellerEvaluated():false;
	}

	@Override
	public void updateInventory(Long id, Integer increaseOrDecrease) {
		
		BeanGood good =  beanGoodDao.findById(id, BeanGood.class);
		good.setInventory(good.getInventory() + increaseOrDecrease);
		
	}

}
